<?php

namespace catchAdmin\externalGoods\controller;

use catchAdmin\externalGoods\excel\tenantGoodsExport;
use catchAdmin\externalGoods\excel\tenantOrdersExport;
use catchAdmin\externalGoods\model\TenantGoods as tenantGoodsModel;
use catchAdmin\externalGoods\model\TenantGoodsAttr as tenantGoodsAttrModel;
use catchAdmin\externalGoods\model\TenantGoodsRule as tenantGoodsRuleModel;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\externalGoods\model\TenantPricePrecent;
use catchAdmin\externalGoods\request\TenantGoodsCreateRequest;
use catchAdmin\externalGoods\service\TenantGoodsService;
use catchAdmin\externalGoods\service\GoodsService as externalGoodsService;
use catchAdmin\permissions\model\Users;
use catcher\base\CatchRequest as Request;
use catcher\library\excel\Excel;
use think\Exception;
use think\facade\Db;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;

class TenantGoods extends CatchAdmin
{

    public function __construct(tenantGoodsModel $tenantGoodsModel,tenantGoodsAttrModel $tenantGoodsAttrModel,tenantGoodsRuleModel $tenantGoodsRuleModel)
    {
        $this->tenantGoodsModel = $tenantGoodsModel;
        $this->tenantGoodsAttrModel = $tenantGoodsAttrModel;
        $this->tenantGoodsRuleModel = $tenantGoodsRuleModel;
    }

    //列表
    public function index(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->tenantGoodsModel->getList($user['tenant_id']));
    }

    //选择商品
    public function select(CatchAuth $auth){
        $user = $auth->user();
        $externalGoodsModel = new externalGoodsModel();

        $result =  $externalGoodsModel->getList2();

        //获取商品是否已经选中
        //$goods_precent = (new Users())->where('id',$)
        $list = $result->each(function(&$item) use ($user){

            //获取商户各种贸易类型成本价
            $tenant_percent = TenantPricePrecent::getPercentByTid($user['qekj_tenant_goods_precent'],$item['trade_type_id']);
            $cost_percent = $tenant_percent['cost_percent'];
//            $price_percent = $tenant_percent['price_percent'];

            $goods_precent  = $cost_percent;

            $item['price'] = number_format(round($item['cost_price'] * $goods_precent),2);

            unset($item['cost_price']);//成本价去掉

            // 列表字段 是否添加
            $id =  $this->tenantGoodsModel->where([
                'syst_goods_id'=>$item['id'],
                'tenant_id'=>$user['tenant_id']
            ])->value('id');
            $item['is_added'] = $id > 0 ;

            $_rule = $item['rule'];
            foreach ($_rule as &$_rule_value){
                $_rule_value['sku_price'] = number_format(round($_rule_value['cost_price'] * $goods_precent),2);
                unset($_rule_value['cost_price']);
            }
            $item['rule'] = $_rule;
        });

        return CatchResponse::paginate($list);
    }

    //添加商品
    public function addSelect(CatchAuth $auth,Request $request){
        $goods_ids = $request->post('goods_ids');

        $tenant_id  = $auth->user()['tenant_id'];

        $tenantGoodsService = new TenantGoodsService;
        $result = $tenantGoodsService->addSelect($goods_ids,$tenant_id);

        return $result;
    }

    //删除商品
    public function delete($id, CatchAuth $auth, Request $request)
    {
        $user = $auth->user();

        $this->tenantGoodsModel->where('tenant_id',$user['tenant_id'])->where('id', $id)->removeOption('soft_delete')->delete();
        $this->tenantGoodsAttrModel->where('tenant_id',$user['tenant_id'])->where('goods_id', $id)->removeOption('soft_delete')->delete();
        $this->tenantGoodsRuleModel->where('tenant_id',$user['tenant_id'])->where('goods_id', $id)->removeOption('soft_delete')->delete();

       // Db::table('db_tenant_goods_attribute')->where('tenant_id',$user['tenant_id'])->where('goods_id',$id)->delete();
       // Db::table('db_tenant_goods_rule')->where('tenant_id',$user['tenant_id'])->where('goods_id',$id)->delete();
        return CatchResponse::success([],'success');
    }
    //创建商品
    public function create(CatchAuth $auth, TenantGoodsCreateRequest $request)
    {
        $params = $request->param();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];

        //添加商品
        $goodsService = new TenantGoodsService();
        $res = $goodsService->createGoods($params, 'add');

        return $res;
    }

    //修改商品
    public function update($id, CatchAuth $auth, TenantGoodsCreateRequest $request)
    {
        $params = $request->param();
        $user = $auth->user();

        $params['tenant_id'] = $user['tenant_id'];
        $params['id'] = $id;

        //修改商品
        $goodsService = new TenantGoodsService();
        $res = $goodsService->editGoods($params, 'edit');

        return $res;
    }

    public function exportGoods(Request $request, Excel $excel,  tenantGoodsExport $tenantGoodsExport){

        return CatchResponse::success($excel->save($tenantGoodsExport, 'export/tenantGoodsExport'));
    }

    //同步商品到巧易商城
    public function addSyncQekjTask(CatchAuth $auth, Request $request){
        $type = $request->param('type');//类型 all section
        $cover = $request->param('cover');//覆盖
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
//        $redis->connect('120.48.65.172', 6379);
//        $redis->auth('1243172690');
        $redis->auth('QiAoYi1234.5678.');
        $redis->select(3);
        $tenant_id = $auth->user()['tenant_id'];

        $task_id = 'syncQekjTask' . $tenant_id .  date('YmdHis');

        if('all' == $type){
            $goods_ids = $this->tenantGoodsModel->where('tenant_id',$tenant_id)
                ->order('id','desc')
                ->column('goods_spu');
        }else{
            $goods_ids = $request->param('goods_spus');
        }

        $redis->del($task_id);
        $redis->set($task_id . "Nums" ,count($goods_ids));

        // 定义任务基础信息
        $info = [
            'task_id'=>$task_id,
            'count'=>count($goods_ids),
            'sync_type'=>$type,
            'sync_cover'=>$cover
        ];

        // 将对象存储为Hash类型
        $redis->hMset($task_id . "Info", $info);

        foreach ($goods_ids as $id){
            $redis->lPush($task_id,$id);
        }

        return CatchResponse::success([
            'task_id'=>$task_id,
            'count'=>count($goods_ids)
        ]);
    }

    //处理
    public function dealSyncQekjTask(CatchAuth $auth, Request $request){
        $task_id = $request->post('task_id');
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
//        $redis->connect('120.48.65.172', 6379);
//        $redis->auth('1243172690');
        $redis->auth('QiAoYi1234.5678.');
        $redis->select(3);

        $info=  $redis->hGetAll($task_id . "Info");

        $goods_ids = $redis->lRange($task_id,0,mt_rand(1,10));

        $tenantGoodsService = new TenantGoodsService;

        try {
            $percent = (float) $auth->user()['qekj_tenant_goods_precent'];
            $qekjTenantId = $auth->user()['qekj_tenant_id'];
            if(empty($qekjTenantId) || $qekjTenantId == 0){
                throw new Exception('暂无权限');
            }
            $tenantGoodsService->syncGoodsToQekj($goods_ids,$info['sync_cover'],$qekjTenantId,$percent);

            foreach ($goods_ids as $id){
                $redis->lRem($task_id,$id,1);
            }
        }catch (Exception $exception){
            return CatchResponse::fail('失败，' . $exception->getMessage());
        }

        return CatchResponse::success([
            'sy'=>$redis->lLen($task_id),
            'count'=> $info['count'],
            'taskInfo'=>$info
        ]);
    }

    public function dealSingleGoodsSyncQekj(CatchAuth $auth, Request $request){
        //return CatchResponse::fail('暂不支持手动同步');

        $goods_spu = $request->post('goods_spu');
        $category_id = $request->post('category_id');

        $tenantGoodsService = new TenantGoodsService;

        try {
            $percent = (float) $auth->user()['qekj_tenant_goods_precent'];
            $qekjTenantId = $auth->user()['qekj_tenant_id'];

            if(empty($qekjTenantId)){
                throw new Exception('未配置巧易云商户');
            }

            $tenantGoodsService->syncGoodsToQekj([$goods_spu],1,$qekjTenantId,$percent,$category_id);
        }catch (Exception $exception){
            return CatchResponse::fail('同步失败，' . $exception->getMessage());
        }

        return CatchResponse::success([]);
    }
}